<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name"
                placeholder="请输入查询名称"
                style="width: 200px; margin-right: 20px;"
                class="filter-item"
                @keyup.enter.native="handleFilter" />
      <el-button v-waves
                 class="filter-item"
                 size="small"
                 type="primary"
                 icon="el-icon-search"
                 @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item"
                 style="margin-left: 10px;"
                 size="small"
                 type="primary"
                 icon="el-icon-plus"
                 @click="handleCreate">
        新建
      </el-button>
    </div>
    </br>
    <el-table :key="tableKey"
              v-loading="listLoading"
              :data="list"
              border
              fit
              highlight-current-row
              style="width: 100%;"
              @sort-change="sortChange">
      <el-table-column type="index"
                       fixed
                       label="#" />
      <el-table-column label="名称"
                       fixed
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主键类型"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.idType | idTypeFilter(row.idType ) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="格式化文件名称"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.formatFileName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="父类"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.superClass }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公共字段"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.addSuperEntityColumns }}</span>
        </template>
      </el-table-column>
      <el-table-column label="忽略字段"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.addIgnoreColumns }}</span>
        </template>
      </el-table-column>
      <el-table-column label="禁用UID"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.disableSerialVersionUid | yesOrNoFilter(row.disableSerialVersionUid) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="字段常量"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.enableColumnConstant | yesOrNoFilter(row.enableColumnConstant) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="移除is前缀"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.enableRemoveIsPrefix | yesOrNoFilter(row.enableRemoveIsPrefix) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="字段注解"
                       align="center">
        <template slot-scope="{row}">
          <span>{{ row.enableTableFieldAnnotation | yesOrNoFilter(row.enableTableFieldAnnotation) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="AR"
                       align="center"
                       width="95">
        <template slot-scope="{row}">
          <span>{{ row.enableActiveRecord | yesOrNoFilter(row.enableActiveRecord) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="乐观锁"
                       align="center">
        <el-table-column label="字段名"
                         align="center">
          <template slot-scope="{row}">
            <span>{{ row.versionColumnName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="属性名"
                         align="center">
          <template slot-scope="{row}">
            <span>{{ row.versionPropertyName }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column label="逻辑删除"
                       align="center">
        <el-table-column label="字段名"
                         align="center">
          <template slot-scope="{row}">
            <span>{{ row.logicDeleteColumnName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="属性名"
                         align="center">
          <template slot-scope="{row}">
            <span>{{ row.logicDeletePropertyName }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="操作"
                       align="center"
                       width="200px"
                       fixed="right"
                       class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary"
                     size="mini"
                     @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'"
                     size="mini"
                     type="danger"
                     @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
                :total="total"
                :page.sync="listQuery.pageNo"
                :limit.sync="listQuery.pageSize"
                @pagination="getList" />
    <!--编辑和新增的表单 -->
    <el-dialog :title="textMap[dialogStatus]"
               :visible.sync="dialogFormVisible">
      <el-form ref="dataForm"
               :rules="rules"
               :model="temp"
               label-position="left"
               label-width="200px"
               style="width: 400px; margin-left:50px;">
        <el-form-item label="名称"
                      prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="主键类型"
                      prop="idType">
          <el-select v-model="temp.idType"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in idTypeOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="格式化文件名称"
                      prop="formatFileName">
          <el-input v-model="temp.formatFileName" />
        </el-form-item>
        <el-form-item label="父类"
                      prop="superClass">
          <el-input v-model="temp.superClass" />
        </el-form-item>
        <el-form-item label="公共字段"
                      prop="addSuperEntityColumns">
          <el-input v-model="temp.addSuperEntityColumns"
                    placeholder="字段名英文逗号隔开" />
        </el-form-item>
        <el-form-item label="忽略字段"
                      prop="addIgnoreColumns">
          <el-input v-model="temp.addIgnoreColumns"
                    placeholder="字段名英文逗号隔开" />
        </el-form-item>
        <el-form-item label="禁用UID"
                      prop="disableSerialVersionUid">
          <el-select v-model="temp.disableSerialVersionUid"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="字段常量"
                      prop="enableColumnConstant">
          <el-select v-model="temp.enableColumnConstant"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="移除is前缀"
                      prop="enableRemoveIsPrefix">
          <el-select v-model="temp.enableRemoveIsPrefix"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="字段注解"
                      prop="enableTableFieldAnnotation">
          <el-select v-model="temp.enableTableFieldAnnotation"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="开启AR 模型"
                      prop="enableTableFieldAnnotation">
          <el-select v-model="temp.enableActiveRecord"
                     placeholder="请选择"
                     size="small">
            <el-option v-for="item in yesOrNoOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="乐观锁字段名"
                      prop="versionColumnName">
          <el-input v-model="temp.versionColumnName" />
        </el-form-item>

        <el-form-item label="乐观锁属性名"
                      prop="versionPropertyName">
          <el-input v-model="temp.versionPropertyName" />
        </el-form-item>

        <el-form-item label="逻辑删除字段名"
                      prop="logicDeleteColumnName">
          <el-input v-model="temp.logicDeleteColumnName" />
        </el-form-item>

        <el-form-item label="逻辑删除属性名"
                      prop="logicDeletePropertyName">
          <el-input v-model="temp.logicDeletePropertyName" />
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary"
                   @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible"
               title="Reading statistics">
      <el-table :data="pvData"
                border
                fit
                highlight-current-row
                style="width: 100%">
        <el-table-column prop="key"
                         label="Channel" />
        <el-table-column prop="pv"
                         label="Pv" />
      </el-table>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { page, saveOrUpdate, remove } from '@/api/entity'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 是、否选项
const yesOrNoOptions = [
  { value: 1, label: '是' },
  { value: 0, label: '否' }
]
// 遍历选项，获取数字对应的字符串值
const yesOrNoTypeKeyValue = yesOrNoOptions.reduce((acc, cur) => {
  acc[cur.value] = cur.label
  return acc
}, {})
// 主键类型选项
const idTypeOptions = [
  { value: 0, label: 'AUTO' },
  { value: 1, label: 'NONE' },
  { value: 2, label: 'INPUT' },
  { value: 3, label: 'ASSIGN_ID' },
  { value: 4, label: 'ASSIGN_UUID' }
]
const idTypeKeyValue = idTypeOptions.reduce((acc, cur) => {
  acc[cur.value] = cur.label
  return acc
}, {})
export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter (status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    // 是否值过滤器
    yesOrNoFilter (type) {
      return yesOrNoTypeKeyValue[type]
    },
    // 主键类型过滤器
    idTypeFilter (type) {
      return idTypeKeyValue[type]
    }
  },
  data () {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageSize: 10,
        pageNo: 1,
        name: undefined
      },
      yesOrNoTypeKeyValue,
      yesOrNoOptions,
      idTypeOptions,
      idTypeKeyValue,
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        nameConvert: '',
        superClass: '',
        enableColumnConstant: 0,
        enableChainModel: 0,
        disableSerialVersionUid: 1,
        enableRemoveIsPrefix: 0,
        enableTableFieldAnnotation: 0,
        enableActiveRecord: 0,
        versionColumnName: '',
        versionPropertyName: '',
        logicDeleteColumnName: '',
        logicDeletePropertyName: '',
        naming: '',
        columnNaming: '',
        addSuperEntityColumns: '',
        addIgnoreColumns: '',
        addTableFills: '',
        idType: 0,
        formatFileName: '%sEntity'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        formatFileName: [{ required: true, message: '格式化文件名称不能为空', trigger: 'blur' }],
        idType: [{ required: true, message: '主键类型不能为空', trigger: 'blur' }],
        // timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created () {
    this.getList()
  },
  methods: {
    getList () {
      this.listLoading = true
      page(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 200)
      })
    },
    handleFilter () {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus (row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange (data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID (order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp () {
      this.temp = {
        id: undefined,
        name: '',
        nameConvert: '',
        superClass: '',
        disableSerialVersionUid: 1,
        enableColumnConstant: 0,
        enableChainModel: 0,
        enableRemoveIsPrefix: 0,
        enableTableFieldAnnotation: 0,
        enableActiveRecord: 0,
        versionColumnName: '',
        versionPropertyName: '',
        logicDeleteColumnName: '',
        logicDeletePropertyName: '',
        naming: '',
        columnNaming: '',
        addSuperEntityColumns: '',
        addIgnoreColumns: '',
        addTableFills: '',
        idType: 0,
        formatFileName: '%sEntity'
      }
    },
    // 处理新增确定
    handleCreate () {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp)
          saveOrUpdate(this.temp).then(() => {
            page(this.listQuery).then(response => {
              this.list = response.data
              this.total = response.total
            })
            this.dialogFormVisible = false
            this.$notify({
              title: '提示信息',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate (row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    updateData () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          saveOrUpdate(tempData).then(() => {
            page(this.listQuery).then(response => {
              this.list = response.data
              this.total = response.total
            })
            this.dialogFormVisible = false
            this.$notify({
              title: '提示信息',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除
    handleDelete (row, index) {
      remove(row.id).then(() => {
        page(this.listQuery).then(response => {
          this.list = response.data
          this.total = response.total
        })
        this.$notify({
          title: '提示信息',
          message: '成功删除',
          type: 'success',
          duration: 2000
        })
      })
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
